package com.leyou.gateway.scheduled;

import com.leyou.auth.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppTokenScheduled {

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    public boolean isUserLoginBool() {
        return userLoginBool;
    }

    /**
     * 允许用户登录开关
     */
    private boolean userLoginBool=false;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 提供一个存储token的属性
     */
    private String token;

    /**
     * 获取token相关配置信息
     */
    @Autowired
    private JwtProperties jwtProp;
    /**
     * 调用获取token的feign接口
     */
    @Autowired
    private AuthClient authClient;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void autoAppAuth(){
        while (true){
            try {
                //获取token
                String token = authClient.authorize(jwtProp.getApp().getId(), jwtProp.getApp().getServiceName());
                //把token放入当前对象的token属性中
                this.token = token;
                log.info("【{}服务获取token成功！】", jwtProp.getApp().getServiceName());
                //跳出死循环
                break;
            }catch (Exception e){
                e.printStackTrace();
                log.error("【{}服务获取token失败！】十秒后重试！", jwtProp.getApp().getServiceName());
            }
            try {
                //如果获取不到休息十秒再获取一次
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //限时限量定时任务
    //每月每日上午10：00分钟00秒执行一次，访问入口开关打开10秒后关闭
    @Scheduled(cron = "0 3 11 * * ?")
    public void seckill(){
        this.userLoginBool=true;
        try {
            Thread.sleep(10000);
            this.userLoginBool=false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getToken() {
        return token;
    }
}
